/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package controllers.utils;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Date;
import javax.inject.Named;
import javax.faces.bean.SessionScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import models.User;

/**
 *
 * @author dybvik
 */
@SessionScoped
@Named(value="user")
public class Userbean {
    private String name;
    private String role;
    private String locale;
    private User user = new User();
    DatabaseHjelper dbh = DatabaseHjelper.hent();

    
    /** Creates a new instance of Userbean */
    public Userbean() {
        //getUsernameFromContext();
        //System.out.println(name);
        //getUserData();
    }

    private void getUserData() {
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet res = null;
        try {
            conn = dbh.finnForbindelse();
            stmt = conn.prepareStatement("select * from users where username=?");
            stmt.setString(1, name);
            res = stmt.executeQuery();
            while (res.next()){
                user.setUserID(res.getInt("userID"));
                user.setFirstName(res.getString("userFirstName"));
                user.setLastName(res.getString("userLastName"));
                user.setEmail(res.getString("email"));
                user.setDateRegistered(res.getDate("dateRegistered"));
                //System.out.println(u.toString());
            }
            stmt = conn.prepareStatement("select * from userRole where userName=?");
            stmt.setString(1, name);
            res = stmt.executeQuery();
            while (res.next()){
                user.setRole(res.getString("role"));
            }
            stmt = conn.prepareStatement("UPDATE users SET dateLastLoggedIn=? WHERE userName=?");
            stmt.setTimestamp(1, utilDateToSqlTimestamp());
            stmt.setString(2, name);
            stmt.executeUpdate();
        } catch (SQLException e) {
            //System.out.println("Henting av brukerdata, evt update av dateLastLoggedin feilet: " + e.getMessage());
        } finally {
            DatabaseHjelper.lukk(res);
            DatabaseHjelper.lukk(stmt);
            DatabaseHjelper.lukk(conn);
        }
    }

    private void getUsernameFromContext() {
        ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
        Object requestObject = context.getRequest();
        if (!(requestObject instanceof HttpServletRequest)) {
            return;
        }
        HttpServletRequest request = (HttpServletRequest) requestObject;
        name = request.getRemoteUser();
    }

    /**
     * Metode for å logge brukeren ut av applikasjonen, og returnerer brukeren til forsiden.
     * @throws IOException
     */
    public void logout() throws IOException {
        ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
        Object requestObject = context.getRequest();
        HttpServletRequest request = (HttpServletRequest) requestObject;
        HttpServletResponse response = (HttpServletResponse) context.getResponse();
        HttpSession session = (HttpSession) context.getSession(false);
        session.invalidate();
        request.getSession().invalidate();

        response.sendRedirect("../faces/index.xhtml"); // "../faces/index.xhtml"
    }

    /**
     * Metode som sjekker om brukeren er logget inn.
     * @return
     */
    public Boolean getCheckLogin() {
        if (getName().equals("") == false) {
            return false;
        }
        return true;
    }

    /**
     * Metode som henter returnerer brukernavnet til brukeren.
     * @return
     */
    public String getName() {
        if (name == null) {
            getUsernameFromContext();
        }
        return name == null ? "" : name;
    }


    /**
     * Metoder for å sjekke rollen til brukeren.
     * @param userRole
     * @return
     */

    private Boolean getRole(String userRole){
        ExternalContext external = FacesContext.getCurrentInstance().getExternalContext();
        HttpServletRequest request = (HttpServletRequest) external.getRequest();
        boolean isRole = request.isUserInRole(userRole);
        //System.out.println("Simonsays: " + external.toString() + " MELLOMROM " + request.toString());
        if(isRole){
            name = userRole;
            //setRole(userRole);
        }
        return isRole;
    }

    // <editor-fold defaultstate="collapsed" desc="Boolean methods to check if the user is in a role">
    private void writeRoleToBean(boolean isRole, String userRole){
        if(isRole==true) role = userRole;
    }

    public Boolean getIsSysadmin(){
        String userRole="sysadmin";
        return getRole(userRole);
    }

    public Boolean getIsTeacher(){
        String userRole="teacher";
        return getRole(userRole);
    }

    public Boolean getIsStudyadmin(){
        String userRole="studyadmin";
        return getRole(userRole);
    }

    public Boolean getIsAdminresource(){
        String userRole="adminresource";
        return getRole(userRole);
    }

    public Boolean getIsGuest(){
        String userRole="guest";
        return getRole(userRole);
    }

    // </editor-fold>

    public String getRole() {
        return role;
    }

    private void setRole(String userRole){
        role = userRole;
    }

    private String getDateToSql() {
        Date date = new Date();

        return date.toString();
    }
    
   private java.sql.Timestamp utilDateToSqlTimestamp() {
        Timestamp  ts = new Timestamp(new Date().getTime());
        user.setDateLastLoggedIn(ts);
        //System.out.println(ts.toString());
        return ts;
        //return new java.sql.Timestamp(utilDate.getTime());
    }

    public String getLocale() {
        if(locale==null){
            FacesContext context = FacesContext.getCurrentInstance();
            System.out.println("Current locale: " + context.getViewRoot().getLocale().getDisplayCountry());
            setLocale(context.getViewRoot().getLocale().getDisplayCountry());
        }
        return locale;
    }

    public void setLocale(String locale) {
        this.locale = locale;
    }



    /*
     setningA = forbindelse.prepareStatement("insert into studieoekt(emnenr, brukernavn, dato, antTimer, aktivitetNr) VALUES(?, ?, ?, ?, ?)");
                setningA.setInt(1, emneNummer);
                setningA.setString(2, brukernavn);
                setningA.setDate(3, konverterJavaDatoTilSqlDato(dato));
                setningA.setDouble(4, antTimer);
                setningA.setInt(5, aktivitetsNummer);
                setningA.executeUpdate();
     */
}